package com.zhenzu.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Runnable和Callable接口的区别：
 * 1.Callable接口有返回值，Runnable接口没有返回值
 * 2.Callable会抛出异常，Runnable不会抛出异常
 * 3.Callable用的call方法，Runnable用的是run方法
 * 在创建线程是，不能在new Thread中直接传入Callable，需要使用中间人FutureTask
 */
class MyThreadRunnable implements Runnable {

    @Override
    public void run() {

    }
}

class MyThreadCallable implements Callable {
    @Override
    public Integer call() throws Exception {
        return 200;
    }
}

public class MyCallable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // Runnable接口创建线程
        new Thread(new MyThreadRunnable(), "AA").start();

        // Callable接口创建线程
        FutureTask<Integer> futureTask1 = new FutureTask<>(new MyThreadCallable());

        // lambda表达式：
        FutureTask<Integer> futureTask2 = new FutureTask<>(() -> {
            System.out.println(Thread.currentThread().getName() + " come in");
            return 1024;
        });


        new Thread(futureTask2, "lucy").start();
        new Thread(futureTask1, "mery").start();


//        while (!futureTask2.isDone()) {
//            System.out.println("wait.....");
//        }

        System.out.println(futureTask2.get());

        System.out.println(futureTask1.get());

        System.out.println(Thread.currentThread().getName() + " over");

        // FutureTask原理：未来任务


    }
}
